راهنمای کامل ساخت xcli

ساخت گام‌به‌گام ابزار CLI برای تولید و مدیریت برنامه‌های مبتنی بر xFramework، با الگوبرداری از xClient و سازگار با محدودیت‌های نسخه‌ای @angular/cli@12.0.4 و @ionic/cli@6.6.0.

Node ≥ 14 Angular CLI 12.0.4 Ionic CLI 6.6.0 Commander.js Handlebars ts-morph CommonJS

۱. مقدمه و اهداف

پروژه xClient یک اپلیکیشن کامل و بالغ بر پایه Ionic/Angular است که با سه بسته اصلی x-framework-core، x-framework-services، x-framework-components، x-framework-identity-sdk، x-framework-push-service و x-saherelm-api-sdk ساخته شده است. این پروژه الگوی کاملی از ساختار پوشه‌ها، الگوهای کدنویسی، پیکربندی و مدیریت Localization/Routing/State را در خود دارد.

هدف این سند طراحی و پیاده‌سازی ابزاری به نام xcli است که با الهام از ساختار xClient، چرخه توسعه یک برنامه xFramework را خودکار کند:

🎯 اهداف عملکردی

  • ساخت پروژه جدید از صفر با یک دستور
  • افزودن موجودیت (DTO + 4 سرویس + Facade)
  • افزودن صفحه مدیریت و اکسپلورر
  • حذف صفحه با پاکسازی همه ارجاعات
  • مدیریت کلیدهای ترجمه
  • بررسی سلامت پروژه (doctor)
  • Build و تحلیل باندل

⚠️ محدودیت‌ها

  • Angular CLI باید 12.0.4 باشد
  • Ionic CLI باید 6.6.0 باشد
  • پروژه‌های تولیدی باید با Angular 12 کار کنند
  • نمی‌توانیم از Standalone Components استفاده کنیم
  • tsconfig و tsconfig.app.json باید با ViewEngine یا Ivy سازگار باشد
  • ng-packagr نسخه 12

📦 خروجی نهایی

  • پکیج npm به نام xcli
  • قابل نصب با npm i -g xcli
  • قابل استفاده به‌صورت npx xcli
  • مستندسازی شده
  • قابل توسعه با plugin

۲. پیش‌نیازها و نسخه‌ها

نسخه‌های اجباری برای پروژه‌های تولیدی

ابزارنسخهنقش
@angular/cli12.0.4تولید اسکلت پروژه، build و test
@ionic/cli6.6.0Ionic integration، Serve، Build
@angular/core~12.0.0هسته Angular
@ionic/angular^6.0.0کامپوننت‌های Ionic
typescript~4.2.3سازگار با Angular 12
rxjs~6.6.0سازگار با Angular 12
zone.js~0.11.4سازگار با Angular 12
ng-packagr^12.0.0برای build کتابخانه‌ها

نسخه‌های CLI خودمان (xcli)

پکیجنسخهدلیل انتخاب
commander^11.1.0CommonJS، پایدار
inquirer^8.2.6CommonJS (v9 ESM است)
chalk^4.1.2CommonJS (v5 ESM است)
ora^5.4.1CommonJS (v6 ESM است)
handlebars^4.7.8CommonJS
fs-extra^10.1.0CommonJS
ts-morph^15.1.0سازگار با TypeScript 4.3
globby^11.1.0CommonJS (v12+ ESM)
semver^7.5.4CommonJS
نکته حیاتی: Node.js ≥ 14 توصیه می‌شود. برای اطمینان از سازگاری، در package.json مقدار "engines": {"node": ">=14.0.0"} قرار دهید. همچنین تمام پکیج‌ها باید CommonJS باشند؛ اگر نسخه ESM انتخاب شود، باید از "type": "module" در package.json و import syntax استفاده کنید که برای سازگاری بیشتر توصیه نمی‌شود.

۳. تحلیل مرجع: xClient به‌عنوان الگو

برای ساخت xcli، ابتدا ساختار xClient را استخراج می‌کنیم تا بدانیم چه فایل‌هایی باید تولید شوند.

ساختار هدف پروژه


my-app/
├── angular.json
├── ionic.config.json
├── capacitor.config.json
├── package.json
├── tsconfig.json
├── tsconfig.app.json
├── tslint.json
├── src/
│   ├── index.html
│   ├── main.ts
│   ├── polyfills.ts
│   ├── global.d.ts
│   ├── styles.scss
│   ├── manifest.webmanifest
│   ├── environments/
│   │   ├── environment.ts
│   │   └── environment.prod.ts
│   ├── theme/
│   │   ├── variables.scss
│   │   └── theme.scss
│   └── app/
│       ├── app.module.ts
│       ├── app-routing.module.ts
│       ├── app.component.ts/html/scss
│       ├── config/
│       │   ├── app.config.ts
│       │   ├── x.config.ts
│       │   ├── x-api.config.ts
│       │   ├── page.config.ts
│       │   └── localization.config.ts
│       ├── shared/
│       │   ├── shared.module.ts
│       │   ├── public-api.ts
│       │   └── services/
│       │       └── shared.service.ts
│       ├── pages/
│       │   ├── startup/
│       │   ├── landing/
│       │   ├── home/
│       │   ├── error/
│       │   └── not-authorized/
│       └── views/
│           └── (از قبل با x-framework-components تأمین می‌شود)
└── assets/
    ├── icon/
    ├── image/
    └── audio/

فایل‌های حیاتی که باید patch شوند

فایلمسئولیتکی patch می‌شود
package.jsonافزودن وابستگی‌هاxcli init
app.module.tsimport ماژول‌های xFrameworkxcli init
app-routing.module.tsافزودن route هاpage:add
page.config.tsافزودن PageIndex و Navpage:add
localization.config.tsافزودن کلیدهای ترجمهstring:add
public-api.ts (SDK)export های جدیدentity:add
x-endpoint.typings.tsافزودن Endpoint جدیدentity:add

الگوهای کلیدی قابل تعمیم

Base Page → Concrete

FilesBaseProviderPage ← FilesManagementPage / FilesExplorerPage. xcli باید همین سه فایل را برای هر موجودیت جدید تولید کند.

Entity → 5 Services

هر Entity شامل Dto، EntityService، ProviderService، EntityPushService و Facade است.

Config غول‌آسا

همه config ها در XConfig مرکب از 7 نوع ذخیره و از طریق InjectionToken توزیع می‌شوند.

Localization مرکب

AppResourceIDs + resource های هر دامنه + منابع Shared در یک آرایه ترکیب می‌شوند.

۴. معماری xcli

ساختار پکیج


xcli/
├── package.json                    # وابستگی‌ها + bin
├── README.md
├── bin/
│   └── xcli.js                     # entry point با shebang
├── lib/
│   ├── cli.js                      # Commander bootstrap
│   ├── commands/
│   │   ├── init.js                 # xcli init
│   │   ├── page-add.js             # xcli page:add
│   │   ├── page-remove.js          # xcli page:remove
│   │   ├── entity-add.js           # xcli entity:add
│   │   ├── string-add.js           # xcli string:add
│   │   ├── config.js               # xcli config:show
│   │   ├── build.js                # xcli build
│   │   └── doctor.js               # xcli doctor
│   ├── generators/
│   │   ├── project.js              # تولید پروژه کامل
│   │   ├── page.js                 # تولید صفحه
│   │   ├── entity.js               # تولید موجودیت
│   │   └── string.js               # افزودن ترجمه
│   ├── utils/
│   │   ├── logger.js               # چاپ رنگی
│   │   ├── paths.js                # کشف ریشه‌ها
│   │   ├── fs-helper.js            # render + write
│   │   ├── ast.js                  # ts-morph patch
│   │   └── shell.js                # execSync wrapper
│   └── templates/
│       ├── project/                # قالب‌های پروژه
│       ├── page/                   # قالب‌های صفحه
│       ├── entity/                 # قالب‌های موجودیت
│       └── string/                 # قالب‌های ترجمه
└── .gitignore

نمودار جریان دستور `page:add`


  [User]      [CLI]          [Generator]      [FS/AST]        [Project]
    │           │                │                │                │
    ├─page:add─►│                │                │                │
    │           ├─parse opts────►│                │                │
    │           │                ├─findProjectRoot►│                │
    │           │                │◄───────path────┤                │
    │           │                │                │                │
    │           │                ├─render templates►│                │
    │           │                │                ├─write files────►│
    │           │                │                │                │
    │           │                ├─patch routing──►│                │
    │           │                │                ├─add route──────►│
    │           │                │                │                │
    │           │                ├─patch page config►│                │
    │           │                │                ├─add nav────────►│
    │           │                │                │                │
    │◄──done────┤◄───────────────┤                │                │

تصمیمات کلیدی

تصمیمدلیل
CommonJSسازگاری با Node 14+ و ابزارهایی مثل npx @angular/cli@12.0.4
Shell-out برای initجلوگیری از نوشتن دستی boilerplate Angular (نصب ng new راحت‌تر است)
ts-morph برای patchویرایش امن فایل‌های TypeScript با حفظ فرمت
Handlebars برای templatesساده، بدون وابستگی به runtime Angular
پیکربندی xcli.config.jsهر پروژه می‌تواند مسیرها و کنوانسیون‌های خود را داشته باشد
Dry-run modeاجازه پیش‌نمایش تغییرات قبل از اعمال

فاز ۱ زیرساخت پروژه xcli

ایجاد پوشه پروژه

mkdir xcli && cd xcli

ایجاد package.json

در ادامه کد کامل ارائه می‌شود.

ساختار پوشه‌ها

mkdir -p bin lib/commands lib/generators lib/utils lib/templates

نصب وابستگی‌ها

npm install

پیوند محلی برای تست

npm link (بعد از پیاده‌سازی)

package.json

xcli/package.json
{
  "name": "xcli",
  "version": "1.0.0",
  "description": "xFramework scaffolding CLI (Angular 12 + Ionic 6)",
  "main": "./lib/cli.js",
  "bin": { "xcli": "./bin/xcli.js" },
  "engines": { "node": ">=14.0.0" },
  "files": ["bin", "lib", "README.md"],
  "keywords": ["xframework", "angular", "ionic", "scaffolding"],
  "license": "MIT",
  "dependencies": {
    "chalk": "^4.1.2",
    "commander": "^11.1.0",
    "fs-extra": "^10.1.0",
    "globby": "^11.1.0",
    "handlebars": "^4.7.8",
    "inquirer": "^8.2.6",
    "ora": "^5.4.1",
    "semver": "^7.5.4",
    "ts-morph": "^15.1.0"
  }
}

bin/xcli.js

xcli/bin/xcli.js
#!/usr/bin/env node
'use strict';

require('../lib/cli').run(process.argv).catch((err) => {
  const msg = err && err.message ? err.message : String(err);
  console.error('\x1b[31m✖ ' + msg + '\x1b[0m');
  if (process.env.XCLI_DEBUG) console.error(err);
  process.exit(1);
});
اجرای مجوز: پس از ایجاد، نیاز است فایل را با دستور chmod +x bin/xcli.js (در Linux/Mac) قابل اجرا کنید.

lib/cli.js

xcli/lib/cli.js
'use strict';

const { Command } = require('commander');
const pkg = require('../package.json');

async function run(argv) {
  const program = new Command();

  program
    .name('xcli')
    .version(pkg.version, '-v, --version')
    .description('xFramework scaffolding CLI (Angular 12 + Ionic 6)')
    .option('--debug', 'Show debug output', false)
    .hook('preAction', (cmd) => {
      if (cmd.opts().debug) process.env.XCLI_DEBUG = '1';
    })
    .addHelpText('after', `
Commands:
  init <name>             Create a new xFramework project
  page:add <name>         Add a new page
  page:remove <name>      Remove an existing page
  entity:add <Name>       Add a new entity (DTO + services)
  string:add <key>        Add a localization key
  config:show             Show effective configuration
  build                   Build project with analysis
  doctor                  Check project health

Examples:
  $ xcli init my-app
  $ xcli page:add orders --type=management --entity=Order
  $ xcli entity:add Order --key=string
  $ xcli string:add orders_title --fa=سفارش‌ها --en=Orders
  $ xcli doctor
    `);

  program.addCommand(require('./commands/init'));
  program.addCommand(require('./commands/page-add'));
  program.addCommand(require('./commands/page-remove'));
  program.addCommand(require('./commands/entity-add'));
  program.addCommand(require('./commands/string-add'));
  program.addCommand(require('./commands/config'));
  program.addCommand(require('./commands/build'));
  program.addCommand(require('./commands/doctor'));

  await program.parseAsync(argv);
}

module.exports = { run };

فاز ۲ Utilities

lib/utils/logger.js

xcli/lib/utils/logger.js
'use strict';
const chalk = require('chalk');

module.exports = {
  info:    (m) => console.log(chalk.blue('ℹ ') + m),
  success: (m) => console.log(chalk.green('✔ ') + m),
  warn:    (m) => console.log(chalk.yellow('⚠ ') + m),
  error:   (m) => console.log(chalk.red('✖ ') + m),
  step:    (m) => console.log(chalk.cyan('▶ ') + m),
  dim:     (m) => console.log(chalk.gray(m)),
  header:  (m) => console.log('\n' + chalk.bold.cyan('═══ ' + m + ' ═══')),
};

lib/utils/paths.js

xcli/lib/utils/paths.js
'use strict';
const fs = require('fs');
const path = require('path');

function findProjectRoot(start = process.cwd()) {
  let dir = start;
  for (let i = 0; i < 10; i++) {
    const hasAngular = fs.existsSync(path.join(dir, 'angular.json'));
    const hasModule = fs.existsSync(path.join(dir, 'src/app/app.module.ts'));
    if (hasAngular && hasModule) return dir;
    const parent = path.dirname(dir);
    if (parent === dir) break;
    dir = parent;
  }
  return null;
}

function findSdkRoot(start = process.cwd()) {
  const candidates = [
    'Modules/xApiSDKHolder/projects/x-saherelm-api-sdk',
    'projects/x-saherelm-api-sdk',
    'x-saherelm-api-sdk',
    '../x-saherelm-api-sdk',
  ];
  let dir = start;
  for (let i = 0; i < 10; i++) {
    for (const c of candidates) {
      const full = path.join(dir, c);
      if (fs.existsSync(path.join(full, 'src/public-api.ts'))) return full;
    }
    const parent = path.dirname(dir);
    if (parent === dir) break;
    dir = parent;
  }
  return null;
}

function loadProjectConfig(root) {
  const cfgPath = path.join(root, 'xcli.config.js');
  if (!fs.existsSync(cfgPath)) {
    return {
      paths: {
        app: 'src/app',
        pages: 'src/app/pages',
        config: 'src/app/config',
      },
      conventions: {
        pageNamePattern: 'kebab-case',
        entityNamePattern: 'PascalCase',
        entityKeyDefault: 'string',
      },
    };
  }
  try {
    return require(cfgPath);
  } catch (e) {
    return {};
  }
}

module.exports = { findProjectRoot, findSdkRoot, loadProjectConfig };

lib/utils/fs-helper.js

xcli/lib/utils/fs-helper.js
'use strict';
const fse = require('fs-extra');
const path = require('path');
const Handlebars = require('handlebars');

// helpers
Handlebars.registerHelper('lower', (s) => s ? String(s).toLowerCase() : '');
Handlebars.registerHelper('upper', (s) => s ? String(s).toUpperCase() : '');
Handlebars.registerHelper('camel', (s) => s ? s.charAt(0).toLowerCase() + s.slice(1) : '');
Handlebars.registerHelper('pascal', (s) => s ? s.charAt(0).toUpperCase() + s.slice(1) : '');
Handlebars.registerHelper('kebab', (s) => s ? String(s).replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase() : '');
Handlebars.registerHelper('plural', (s) => s ? s + 's' : '');
Handlebars.registerHelper('eq', (a, b) => a === b);
Handlebars.registerHelper('not', (v) => !v);
Handlebars.registerHelper('json', (v) => JSON.stringify(v, null, 2));
Handlebars.registerHelper('date', () => new Date().toISOString().slice(0, 10));

async function renderTemplateFile(tplPath, data) {
  const src = await fse.readFile(tplPath, 'utf8');
  const tpl = Handlebars.compile(src, { noEscape: true });
  return tpl(data);
}

async function writeFromTemplate(tplPath, outPath, data) {
  const content = await renderTemplateFile(tplPath, data);
  await fse.ensureDir(path.dirname(outPath));
  await fse.writeFile(outPath, content, 'utf8');
  return outPath;
}

async function renderString(tplString, data) {
  const tpl = Handlebars.compile(tplString, { noEscape: true });
  return tpl(data);
}

module.exports = { renderTemplateFile, writeFromTemplate, renderString };

lib/utils/ast.js (با ts-morph)

xcli/lib/utils/ast.js
'use strict';
const path = require('path');
const { Project, SyntaxKind } = require('ts-morph');
const fse = require('fs-extra');

function toPascal(name) {
  return name.split('-').map(p => p.charAt(0).toUpperCase() + p.slice(1)).join('');
}

// ─── app-routing.module.ts patch ───
function patchAppRoutingModule({ root, name, type, route }) {
  const file = path.join(root, 'src/app/app-routing.module.ts');
  const project = new Project();
  const source = project.addSourceFileAtPath(file);
  const Name = toPascal(name);

  if (type === 'management' || type === 'explorer') {
    const routes = source.getVariableDeclaration('routes');
    if (!routes) return;
    const arr = routes.getInitializerIfKind(SyntaxKind.ArrayLiteralExpression);
    if (!arr) return;

    const marker = `./pages/${name}`;
    if (source.getFullText().includes(marker)) return;

    arr.addElement(`{
    path: '${route}',
    loadChildren: () => import('./pages/${name}/${name}-page.module').then(
      (m) => m.${Name}PageModule
    ),
  }`);
  }
  source.saveSync();
}

// ─── page.config.ts patch ───
function patchPageConfig({ root, name, type, route }) {
  const file = path.join(root, 'src/app/config/page.config.ts');
  const project = new Project();
  const source = project.addSourceFileAtPath(file);
  const Name = toPascal(name);
  const routeKey = name.replace(/-/g, '');

  // 1) AppRoutes enum
  const appRoutes = source.getEnum('AppRoutes');
  if (appRoutes && !appRoutes.getMember(Name)) {
    appRoutes.addMember({ name: Name, initializer: `'${route}'` });
  }

  // 2) PageIndex
  const pageIndex = source.getVariableDeclaration('PageIndex');
  if (pageIndex) {
    const init = pageIndex.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression);
    if (init && !init.getProperty(Name)) {
      init.addPropertyAssignment({
        name: Name,
        initializer: `{
    id: \`\${PageName.${Name}}\`,
    name: \`\${PageName.${Name}}\`,
    title: AppResourceIDs.${name}_page_title,
    description: AppResourceIDs.${name}_page_description,
    baseRoute: \`\${AppRoutes.${Name}}\`,
    route: ['/', \`\${AppRoutes.${Name}}\`],
    icon: XIconNames.posts,
  }`,
      });
    }
  }

  // 3) Pages object
  const pages = source.getVariableDeclaration('Pages');
  if (pages) {
    const init = pages.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression);
    if (init && !init.getProperty(Name)) {
      init.addPropertyAssignment({
        name: Name,
        initializer: `PageIndex.${Name}`,
      });
    }
  }

  source.saveSync();
}

// ─── localization patch ───
function patchLocalization({ root, key, fa, en }) {
  const file = path.join(root, 'src/app/config/localization.config.ts');
  const project = new Project();
  const source = project.addSourceFileAtPath(file);

  // 1) AppResourceIDs enum
  const enumDecl = source.getEnum('AppResourceIDs');
  if (enumDecl && !enumDecl.getMember(key)) {
    enumDecl.addMember({ name: key, initializer: `'${key}'` });
  }

  // 2) persian array resource entries
  const persian = source.getVariableDeclaration('persianResources');
  if (persian && fa) {
    const arr = persian.getInitializerIfKind(SyntaxKind.ArrayLiteralExpression);
    if (arr && !source.getFullText().includes(`id: '${key}'`)) {
      arr.addElement(`{ id: '${key}', value: '${fa}' }`);
    }
  }

  const english = source.getVariableDeclaration('englishResources');
  if (english && en) {
    const arr = english.getInitializerIfKind(SyntaxKind.ArrayLiteralExpression);
    if (arr && !source.getFullText().includes(`id: '${key}'`)) {
      arr.addElement(`{ id: '${key}', value: '${en}' }`);
    }
  }

  source.saveSync();
}

// ─── x-endpoint patch ───
function patchEndpoints({ sdkRoot, Name, pluralName }) {
  const file = path.join(sdkRoot, 'src/lib/typings/x-endpoint.typings.ts');
  const project = new Project();
  const source = project.addSourceFileAtPath(file);

  const apiEndPoint = source.getEnum('XApiEndPoint');
  if (apiEndPoint) {
    if (!apiEndPoint.getMember(`${Name}Entity`)) {
      apiEndPoint.addMember({
        name: `${Name}Entity`,
        initializer: `'Entities/${pluralName}'`,
      });
    }
    if (!apiEndPoint.getMember(`${Name}Service`)) {
      apiEndPoint.addMember({
        name: `${Name}Service`,
        initializer: `'Services/${pluralName}'`,
      });
    }
  }

  source.saveSync();
}

// ─── public-api patch ───
function patchPublicApi({ sdkRoot, Name }) {
  const file = path.join(sdkRoot, 'src/public-api.ts');
  const project = new Project();
  const source = project.addSourceFileAtPath(file);
  const lower = Name.charAt(0).toLowerCase() + Name.slice(1);

  const exports = [
    `export * from './lib/${lower}/models/x-${lower}.dto';`,
    `export * from './lib/${lower}/services/x-${lower}.entity.service';`,
    `export * from './lib/${lower}/services/x-${lower}.provider.service';`,
    `export * from './lib/${lower}/services/x-${lower}.entity.push.service';`,
    `export * from './lib/${lower}/x-${lower}.services';`,
  ];

  for (const line of exports) {
    if (!source.getFullText().includes(line)) {
      source.addStatements('\n' + line);
    }
  }
  source.saveSync();
}

module.exports = {
  patchAppRoutingModule,
  patchPageConfig,
  patchLocalization,
  patchEndpoints,
  patchPublicApi,
  toPascal,
};

lib/utils/shell.js

xcli/lib/utils/shell.js
'use strict';
const { execSync } = require('child_process');

function run(cmd, opts = {}) {
  return execSync(cmd, {
    stdio: opts.silent ? 'pipe' : 'inherit',
    cwd: opts.cwd || process.cwd(),
    encoding: 'utf8',
    ...opts,
  });
}

module.exports = { run };

فاز ۳ Commands

lib/commands/init.js

xcli/lib/commands/init.js
'use strict';

const { Command } = require('commander');
const path = require('path');
const fse = require('fs-extra');
const ora = require('ora');
const inquirer = require('inquirer');
const logger = require('../utils/logger');
const shell = require('../utils/shell');
const { generateProject } = require('../generators/project');

module.exports = new Command('init')
  .description('Create a new xFramework project (Angular 12 + Ionic 6)')
  .argument('<name>', 'Project name (kebab-case)')
  .option('-d, --dir <dir>', 'Target directory', process.cwd())
  .option('--skip-install', 'Skip npm install', false)
  .option('--base-api <url>', 'Base API URL', 'https://localhost:5001/')
  .option('--hub-url <url>', 'SignalR hub URL', 'https://localhost:5001/')
  .option('--dry-run', 'Preview commands without executing', false)
  .action(async (name, opts) => {
    if (!/^[a-z][a-z0-9-]*$/.test(name)) {
      logger.error('Project name must be kebab-case (e.g. my-app)');
      process.exit(1);
    }

    const target = path.resolve(opts.dir, name);

    // handle existing dir
    if (await fse.pathExists(target)) {
      if (opts.dryRun) {
        logger.warn(`(dry-run) Would overwrite ${target}`);
        return;
      }
      const { overwrite } = await inquirer.prompt([
        {
          type: 'confirm', name: 'overwrite',
          message: `Directory "${name}" exists. Overwrite?`,
          default: false,
        },
      ]);
      if (!overwrite) { logger.warn('Aborted.'); return; }
      await fse.remove(target);
    }

    // step 1: ng new (Angular 12.0.4)
    logger.header('Step 1/3: Creating Angular 12 project');
    const ngCmd = `npx -y @angular/cli@12.0.4 new ${name} --routing --style=scss --skip-git --skip-install --strict=false`;
    logger.dim('$ ' + ngCmd);
    if (!opts.dryRun) {
      const sp = ora('Running ng new...').start();
      try {
        shell.run(ngCmd, { cwd: opts.dir });
        sp.succeed('Angular project created');
      } catch (e) {
        sp.fail('ng new failed');
        throw e;
      }
    }

    // step 2: patch for xFramework
    logger.header('Step 2/3: Patching for xFramework');
    if (!opts.dryRun) {
      const sp = ora('Applying xFramework patches...').start();
      try {
        await generateProject({ name, target, opts });
        sp.succeed('xFramework patches applied');
      } catch (e) {
        sp.fail('Patch failed: ' + e.message);
        throw e;
      }
    } else {
      logger.warn(`(dry-run) Would patch ${target}`);
    }

    // step 3: install
    if (!opts.skipInstall && !opts.dryRun) {
      logger.header('Step 3/3: Installing dependencies');
      const sp = ora('Running npm install (legacy-peer-deps)...').start();
      try {
        shell.run('npm install --legacy-peer-deps', { cwd: target });
        sp.succeed('Dependencies installed');
      } catch (e) {
        sp.warn('npm install failed; try manually: cd ' + name + ' && npm install --legacy-peer-deps');
      }
    }

    logger.header('✔ Done');
    logger.info(`Project created at: ${target}`);
    logger.info('Next steps:');
    logger.dim(`  cd ${name}`);
    logger.dim('  npm start');
    logger.dim('  xcli page:add home');
    logger.dim('  xcli entity:add Product');
  });

lib/commands/page-add.js

xcli/lib/commands/page-add.js
'use strict';

const { Command } = require('commander');
const path = require('path');
const ora = require('ora');
const logger = require('../utils/logger');
const { findProjectRoot, loadProjectConfig } = require('../utils/paths');
const { generatePage } = require('../generators/page');

module.exports = new Command('page:add')
  .description('Add a new page to the project')
  .argument('<name>', 'Page name (kebab-case)')
  .option('-t, --type <type>', 'management | explorer | auth | custom', 'custom')
  .option('-e, --entity <entity>', 'Associated entity (PascalCase)')
  .option('--route <route>', 'Custom route (default: name)')
  .option('--no-nav', 'Do not add to navigation')
  .option('--dry-run', 'Preview without writing', false)
  .action(async (name, opts) => {
    if (!/^[a-z][a-z0-9-]*$/.test(name)) {
      logger.error('Page name must be kebab-case');
      process.exit(1);
    }
    const root = findProjectRoot();
    if (!root) {
      logger.error('Not in an xFramework project (missing angular.json or app.module.ts)');
      process.exit(1);
    }
    const projectConfig = loadProjectConfig(root);

    if (opts.dryRun) {
      logger.header('Dry-run: changes preview');
      logger.info(`Will create page "${name}" of type "${opts.type}"`);
      if (opts.entity) logger.info(`Using entity: ${opts.entity}`);
      logger.info(`Route: /${opts.route || name}`);
      logger.info(`Add to navigation: ${opts.nav}`);
      return;
    }

    const sp = ora(`Generating page "${name}"...`).start();
    try {
      const files = await generatePage({
        root,
        name,
        type: opts.type,
        entity: opts.entity,
        route: opts.route || name,
        addToNav: opts.nav,
        config: projectConfig,
      });
      sp.succeed(`Page "${name}" generated`);
      logger.header('Files created/modified:');
      files.forEach((f) => logger.dim('  + ' + path.relative(root, f)));
      logger.info('');
      logger.success('Run "npm start" to test the page');
    } catch (e) {
      sp.fail('Failed: ' + e.message);
      throw e;
    }
  });

lib/commands/entity-add.js

xcli/lib/commands/entity-add.js
'use strict';

const { Command } = require('commander');
const path = require('path');
const ora = require('ora');
const logger = require('../utils/logger');
const { findSdkRoot } = require('../utils/paths');
const { generateEntity } = require('../generators/entity');

module.exports = new Command('entity:add')
  .description('Add a new entity to the API SDK (DTO + services + push + facade)')
  .argument('<Name>', 'Entity name (PascalCase, e.g. Order)')
  .option('--key <type>', 'Key type: string | number', 'string')
  .option('--plural <plural>', 'Plural name (default: Name + s)')
  .option('--with-push', 'Include SignalR push service', true)
  .option('--with-provider', 'Include provider service', true)
  .option('--endpoint <path>', 'API endpoint base path')
  .option('--dry-run', 'Preview without writing', false)
  .action(async (Name, opts) => {
    if (!/^[A-Z][A-Za-z0-9]*$/.test(Name)) {
      logger.error('Entity name must be PascalCase (e.g. Order, OrderItem)');
      process.exit(1);
    }
    const sdkRoot = findSdkRoot();
    if (!sdkRoot) {
      logger.error('Cannot find x-saherelm-api-sdk root');
      process.exit(1);
    }

    if (opts.dryRun) {
      logger.header('Dry-run: entity generation preview');
      logger.info(`Entity: ${Name}`);
      logger.info(`Key type: ${opts.key}`);
      logger.info(`With push: ${opts.withPush}`);
      logger.info(`With provider: ${opts.withProvider}`);
      logger.info('Files:');
      logger.dim(`  src/lib/${Name.toLowerCase()}/models/x-${Name.toLowerCase()}.dto.ts`);
      logger.dim(`  src/lib/${Name.toLowerCase()}/services/x-${Name.toLowerCase()}.entity.service.ts`);
      if (opts.withProvider) logger.dim(`  ...provider service`);
      if (opts.withPush) logger.dim(`  ...push service`);
      logger.dim(`  src/lib/${Name.toLowerCase()}/x-${Name.toLowerCase()}.services.ts`);
      return;
    }

    const sp = ora(`Generating entity "${Name}"...`).start();
    try {
      const files = await generateEntity({
        sdkRoot,
        Name,
        keyType: opts.key,
        pluralName: opts.plural || (Name + 's'),
        withPush: opts.withPush,
        withProvider: opts.withProvider,
        endpoint: opts.endpoint,
      });
      sp.succeed(`Entity "${Name}" generated`);
      logger.header('Files created/modified:');
      files.forEach((f) => logger.dim('  + ' + path.relative(sdkRoot, f)));
    } catch (e) {
      sp.fail('Failed: ' + e.message);
      throw e;
    }
  });

lib/commands/string-add.js

xcli/lib/commands/string-add.js
'use strict';

const { Command } = require('commander');
const ora = require('ora');
const logger = require('../utils/logger');
const { findProjectRoot } = require('../utils/paths');
const { addStringKey } = require('../generators/string');

module.exports = new Command('string:add')
  .description('Add a localization key to project languages')
  .argument('<key>', 'Resource key (snake_case)')
  .option('--fa <text>', 'Persian translation')
  .option('--en <text>', 'English translation')
  .option('--dry-run', 'Preview without writing', false)
  .action(async (key, opts) => {
    if (!/^[a-z][a-z0-9_]*$/.test(key)) {
      logger.error('Key must be snake_case (e.g. orders_title)');
      process.exit(1);
    }
    if (!opts.fa && !opts.en) {
      logger.error('Provide at least --fa or --en');
      process.exit(1);
    }
    const root = findProjectRoot();
    if (!root) { logger.error('Not in xFramework project'); process.exit(1); }

    if (opts.dryRun) {
      logger.header('Dry-run: string add preview');
      logger.info(`Key: ${key}`);
      if (opts.fa) logger.info(`FA: ${opts.fa}`);
      if (opts.en) logger.info(`EN: ${opts.en}`);
      return;
    }

    const sp = ora(`Adding localization key "${key}"...`).start();
    try {
      await addStringKey({ root, key, fa: opts.fa, en: opts.en });
      sp.succeed(`Key "${key}" added`);
    } catch (e) {
      sp.fail('Failed: ' + e.message);
      throw e;
    }
  });

lib/commands/doctor.js

xcli/lib/commands/doctor.js
'use strict';

const { Command } = require('commander');
const fs = require('fs');
const path = require('path');
const chalk = require('chalk');
const logger = require('../utils/logger');
const { findProjectRoot } = require('../utils/paths');

module.exports = new Command('doctor')
  .description('Check project health')
  .action(async () => {
    const root = findProjectRoot();
    if (!root) {
      logger.error('Not in an xFramework project');
      process.exit(1);
    }

    const checks = [];
    const add = (name, ok, fix) => checks.push({ name, ok, fix });

    // package.json
    let pkg = {};
    try { pkg = require(path.join(root, 'package.json')); } catch {}
    add('package.json exists', !!pkg.name, 'Run xcli init');

    // Angular + Ionic
    add('@angular/core installed', !!pkg.dependencies?.['@angular/core'], 'npm i @angular/core@~12.0.0');
    add('@ionic/angular installed', !!pkg.dependencies?.['@ionic/angular'], 'npm i @ionic/angular@^6.0.0');

    // x-framework
    ['x-framework-core', 'x-framework-services', 'x-framework-components',
     'x-framework-identity-sdk', 'x-framework-push-service', 'x-saherelm-api-sdk']
      .forEach(lib => {
        add(
          `${lib} installed`,
          !!pkg.dependencies?.[lib] || !!pkg.devDependencies?.[lib],
          `npm i ${lib}`
        );
      });

    // key files
    [
      'src/app/app.module.ts',
      'src/app/app-routing.module.ts',
      'src/app/config/x.config.ts',
      'src/app/config/x-api.config.ts',
      'src/app/config/app.config.ts',
      'src/app/config/page.config.ts',
      'src/app/config/localization.config.ts',
      'src/app/shared/shared.module.ts',
      'src/environments/environment.ts',
      'src/theme/variables.scss',
      'src/theme/theme.scss',
      'ionic.config.json',
      'capacitor.config.json',
    ].forEach(f => add(`${f} exists`, fs.existsSync(path.join(root, f)), 'Re-init project'));

    // report
    logger.header('Project Health Check');
    let pass = 0, fail = 0;
    checks.forEach((c) => {
      if (c.ok) { logger.success(c.name); pass++; }
      else {
        logger.error(c.name + '  →  ' + (c.fix || ''));
        fail++;
      }
    });
    logger.info('');
    console.log(
      chalk.bold('Summary: ') +
      chalk.green(`${pass} passed`) +
      ', ' +
      (fail > 0 ? chalk.red(`${fail} failed`) : chalk.gray('0 failed'))
    );
    process.exit(fail > 0 ? 1 : 0);
  });

lib/commands/page-remove.js (خلاصه)

xcli/lib/commands/page-remove.js
'use strict';

const { Command } = require('commander');
const path = require('path');
const fse = require('fs-extra');
const inquirer = require('inquirer');
const ora = require('ora');
const logger = require('../utils/logger');
const { findProjectRoot } = require('../utils/paths');
const ast = require('../utils/ast');

module.exports = new Command('page:remove')
  .description('Remove an existing page and clean all references')
  .argument('<name>', 'Page name (kebab-case)')
  .option('--force', 'Skip confirmation', false)
  .action(async (name, opts) => {
    const root = findProjectRoot();
    if (!root) { logger.error('Not in project'); process.exit(1); }

    const pageDir = path.join(root, 'src/app/pages', name);
    if (!(await fse.pathExists(pageDir))) {
      logger.error(`Page "${name}" not found at ${pageDir}`);
      process.exit(1);
    }

    if (!opts.force) {
      const { confirm } = await inquirer.prompt([
        { type: 'confirm', name: 'confirm', message: `Delete page "${name}" and clean all references?`, default: false },
      ]);
      if (!confirm) { logger.warn('Aborted'); return; }
    }

    const</